// src/config/scenarios.rs

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use anyhow::{Result, anyhow};

/// 应用场景配置集合
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScenarioConfigs {
    /// 生产制造场景配置
    pub manufacturing: ManufacturingConfig,
    /// 机器人应用场景配置
    pub robotics: RoboticsConfig,
    /// 供应链管理场景配置
    pub supply_chain: SupplyChainConfig,
    /// 交通工程场景配置
    pub transportation: TransportationConfig,
    /// 科研教学场景配置
    pub research_education: ResearchEducationConfig,
    /// 公共事业场景配置
    pub public_utilities: PublicUtilitiesConfig,
    /// 园区运营场景配置
    pub campus_operations: CampusOperationsConfig,
}

impl ScenarioConfigs {
    /// 获取所有启用的场景
    pub fn enabled_scenarios(&self) -> Vec<&str> {
        let mut scenarios = Vec::new();
        
        if self.manufacturing.enabled {
            scenarios.push("manufacturing");
        }
        if self.robotics.enabled {
            scenarios.push("robotics");
        }
        if self.supply_chain.enabled {
            scenarios.push("supply_chain");
        }
        if self.transportation.enabled {
            scenarios.push("transportation");
        }
        if self.research_education.enabled {
            scenarios.push("research_education");
        }
        if self.public_utilities.enabled {
            scenarios.push("public_utilities");
        }
        if self.campus_operations.enabled {
            scenarios.push("campus_operations");
        }
        
        scenarios
    }
    
    /// 根据场景名称获取配置
    pub fn get_scenario_config(&self, scenario_name: &str) -> Option<&dyn ScenarioConfig> {
        match scenario_name {
            "manufacturing" => Some(&self.manufacturing),
            "robotics" => Some(&self.robotics),
            "supply_chain" => Some(&self.supply_chain),
            "transportation" => Some(&self.transportation),
            "research_education" => Some(&self.research_education),
            "public_utilities" => Some(&self.public_utilities),
            "campus_operations" => Some(&self.campus_operations),
            _ => None,
        }
    }
}

/// 场景配置trait
pub trait ScenarioConfig {
    fn is_enabled(&self) -> bool;
    fn get_required_models(&self) -> Vec<String>;
    fn get_mapping_rules(&self) -> HashMap<String, String>;
    fn validate_config(&self) -> Result<()>;
    fn get_scenario_type(&self) -> ScenarioType;
}

/// 场景类型枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ScenarioType {
    Manufacturing,
    Robotics,
    SupplyChain,
    Transportation,
    ResearchEducation,
    PublicUtilities,
    CampusOperations,
}

/// 生产制造场景配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManufacturingConfig {
    /// 是否启用生产制造场景
    pub enabled: bool,
    /// 支持的设备类型
    pub supported_device_types: Vec<String>,
    /// 数据采集间隔（秒）
    pub data_collection_interval_secs: u64,
    /// 质量检测标准
    pub quality_standards: Vec<String>,
    /// 物料追溯配置
    pub material_traceability: MaterialTraceabilityConfig,
    /// 生产订单管理配置
    pub production_orders: ProductionOrdersConfig,
    /// 设备监控配置
    pub equipment_monitoring: EquipmentMonitoringConfig,
    /// 质量检测配置
    pub quality_inspection: QualityInspectionConfig,
}

impl ScenarioConfig for ManufacturingConfig {
    fn is_enabled(&self) -> bool {
        self.enabled
    }
    
    fn get_required_models(&self) -> Vec<String> {
        vec,
            "订单/工单".to_string(),
            "生产设备".to_string(),
            "质量检测".to_string(),
            "物料追溯".to_string(),
        ]
    }
    
    fn get_mapping_rules(&self) -> HashMap<String, String> {
        maplit::hashmap! {
            "设备状态".to_string() => "BaseDataVariableType".to_string(),
            "生产订单".to_string() => "ObjectType".to_string(),
            "质量检测结果".to_string() => "BaseDataVariableType".to_string(),
            "物料批次".to_string() => "ObjectType".to_string(),
        }
    }
    
    fn validate_config(&self) -> Result<()> {
        if self.enabled && self.supported_device_types.is_empty() {
            return Err(anyhow!("Manufacturing scenario requires at least one supported device type"));
        }
        if self.data_collection_interval_secs == 0 {
            return Err(anyhow!("Data collection interval must be greater than 0"));
        }
        Ok(())
    }
    
    fn get_scenario_type(&self) -> ScenarioType {
        ScenarioType::Manufacturing
    }
}

/// 机器人应用场景配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoboticsConfig {
    /// 是否启用机器人应用场景
    pub enabled: bool,
    /// 支持的机器人协议
    pub supported_protocols: Vec<String>,
    /// 运动控制精度
    pub motion_control_precision: f64,
    /// 任务调度配置
    pub task_scheduling: TaskSchedulingConfig,
    /// 轨迹规划配置
    pub trajectory_planning: TrajectoryPlanningConfig,
    /// 安全监控配置
    pub safety_monitoring: SafetyMonitoringConfig,
    /// 协作机器人配置
    pub collaborative_robotics: CollaborativeRoboticsConfig,
}

impl ScenarioConfig for RoboticsConfig {
    fn is_enabled(&self) -> bool {
        self.enabled
    }
    
    fn get_required_models(&self) -> Vec<String> {
        vec,
            "任务描述".to_string(),
            "机器人运动轨迹".to_string(),
            "工作环境".to_string(),
            "安全区域".to_string(),
        ]
    }
    
    fn get_mapping_rules(&self) -> HashMap<String, String> {
        maplit::hashmap! {
            "关节位置".to_string() => "BaseDataVariableType".to_string(),
            "任务指令".to_string() => "ObjectType".to_string(),
            "运动轨迹".to_string() => "BaseDataVariableType".to_string(),
            "安全状态".to_string() => "BaseDataVariableType".to_string(),
        }
    }
    
    fn validate_config(&self) -> Result<()> {
        if self.enabled && self.motion_control_precision <= 0.0 {
            return Err(anyhow!("Motion control precision must be greater than 0"));
        }
        if self.enabled && self.supported_protocols.is_empty() {
            return Err(anyhow!("Robotics scenario requires at least one supported protocol"));
        }
        Ok(())
    }
    
    fn get_scenario_type(&self) -> ScenarioType {
        ScenarioType::Robotics
    }
}

/// 供应链管理场景配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SupplyChainConfig {
    /// 是否启用供应链管理场景
    pub enabled: bool,
    /// 库存管理配置
    pub inventory_management: InventoryManagementConfig,
    /// 物流跟踪配置
    pub logistics_tracking: LogisticsTrackingConfig,
    /// 供应商管理配置
    pub supplier_management: SupplierManagementConfig,
    /// 需求预测配置
    pub demand_forecasting: DemandForecastingConfig,
}

impl ScenarioConfig for SupplyChainConfig {
    fn is_enabled(&self) -> bool {
        self.enabled
    }
    
    fn get_required_models(&self) -> Vec<String> {
        vec,
            "BOM".to_string(),
            "订单".to_string(),
            "产品追溯".to_string(),
            "物流信息".to_string(),
        ]
    }
    
    fn get_mapping_rules(&self) -> HashMap<String, String> {
        maplit::hashmap! {
            "库存状态".to_string() => "BaseDataVariableType".to_string(),
            "物流轨迹".to_string() => "ObjectType".to_string(),
            "订单状态".to_string() => "BaseDataVariableType".to_string(),
            "供应商信息".to_string() => "ObjectType".to_string(),
        }
    }
    
    fn validate_config(&self) -> Result<()> {
        // 供应链场景的验证逻辑
        Ok(())
    }
    
    fn get_scenario_type(&self) -> ScenarioType {
        ScenarioType::SupplyChain
    }
}

/// 交通工程场景配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransportationConfig {
    /// 是否启用交通工程场景
    pub enabled: bool,
    /// 交通监控配置
    pub traffic_monitoring: TrafficMonitoringConfig,
    /// 车辆跟踪配置
    pub vehicle_tracking: VehicleTrackingConfig,
    /// 信号控制配置
    pub signal_control: SignalControlConfig,
    /// 路况分析配置
    pub road_condition_analysis: RoadConditionAnalysisConfig,
}

impl ScenarioConfig for TransportationConfig {
    fn is_enabled(&self) -> bool {
        self.enabled
    }
    
    fn get_required_models(&self) -> Vec<String> {
        vec,
            "空间知识".to_string(),
            "交通流量".to_string(),
            "车辆位置".to_string(),
            "路况数据".to_string(),
        ]
    }
    
    fn get_mapping_rules(&self) -> HashMap<String, String> {
        maplit::hashmap! {
            "交通流量".to_string() => "BaseDataVariableType".to_string(),
            "车辆位置".to_string() => "ObjectType".to_string(),
            "信号状态".to_string() => "BaseDataVariableType".to_string(),
            "路况信息".to_string() => "BaseDataVariableType".to_string(),
        }
    }
    
    fn validate_config(&self) -> Result<()> {
        Ok(())
    }
    
    fn get_scenario_type(&self) -> ScenarioType {
        ScenarioType::Transportation
    }
}

/// 科研教学场景配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResearchEducationConfig {
    /// 是否启用科研教学场景
    pub enabled: bool,
    /// 实验数据配置
    pub experimental_data: ExperimentalDataConfig,
    /// 学术集成配置
    pub academic_integration: AcademicIntegrationConfig,
    /// 教学资源配置
    pub teaching_resources: TeachingResourcesConfig,
    /// 科研协作配置
    pub research_collaboration: ResearchCollaborationConfig,
}

impl ScenarioConfig for ResearchEducationConfig {
    fn is_enabled(&self) -> bool {
        self.enabled
    }
    
    fn get_required_models(&self) -> Vec<String> {
        vec,
            "测量仪器".to_string(),
            "执行机构".to_string(),
            "实验报告系统".to_string(),
            "学术标准".to_string(),
        ]
    }
    
    fn get_mapping_rules(&self) -> HashMap<String, String> {
        maplit::hashmap! {
            "实验数据".to_string() => "BaseDataVariableType".to_string(),
            "仪器状态".to_string() => "ObjectType".to_string(),
            "实验进度".to_string() => "BaseDataVariableType".to_string(),
            "学术指标".to_string() => "BaseDataVariableType".to_string(),
        }
    }
    
    fn validate_config(&self) -> Result<()> {
        Ok(())
    }
    
    fn get_scenario_type(&self) -> ScenarioType {
        ScenarioType::ResearchEducation
    }
}

/// 公共事业场景配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublicUtilitiesConfig {
    /// 是否启用公共事业场景
    pub enabled: bool,
    /// 公用事业监控配置
    pub utility_monitoring: UtilityMonitoringConfig,
    /// 资源管理配置
    pub resource_management: ResourceManagementConfig,
    /// 公共服务配置
    pub public_services: PublicServicesConfig,
    /// 应急响应配置
    pub emergency_response: EmergencyResponseConfig,
}

impl ScenarioConfig for PublicUtilitiesConfig {
    fn is_enabled(&self) -> bool {
        self.enabled
    }
    
    fn get_required_models(&self) -> Vec<String> {
        vec,
            "资源消耗".to_string(),
            "服务状态".to_string(),
            "用户需求".to_string(),
            "应急资源".to_string(),
        ]
    }
    
    fn get_mapping_rules(&self) -> HashMap<String, String> {
        maplit::hashmap! {
            "设施状态".to_string() => "BaseDataVariableType".to_string(),
            "资源消耗".to_string() => "BaseDataVariableType".to_string(),
            "服务请求".to_string() => "ObjectType".to_string(),
            "应急状态".to_string() => "BaseDataVariableType".to_string(),
        }
    }
    
    fn validate_config(&self) -> Result<()> {
        Ok(())
    }
    
    fn get_scenario_type(&self) -> ScenarioType {
        ScenarioType::PublicUtilities
    }
}

/// 园区运营场景配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CampusOperationsConfig {
    /// 是否启用园区运营场景
    pub enabled: bool,
    /// 设施管理配置
    pub facility_management: FacilityManagementConfig,
    /// 能源管理配置
    pub energy_management: EnergyManagementConfig,
    /// 安全管理配置
    pub security_management: SecurityManagementConfig,
    /// 环境监控配置
    pub environmental_monitoring: EnvironmentalMonitoringConfig,
}

impl ScenarioConfig for CampusOperationsConfig {
    fn is_enabled(&self) -> bool {
        self.enabled
    }
    
    fn get_required_models(&self) -> Vec<String> {
        vec,
            "能源消耗".to_string(),
            "安全设备".to_string(),
            "环境参数".to_string(),
            "运营指标".to_string(),
        ]
    }
    
    fn get_mapping_rules(&self) -> HashMap<String, String> {
        maplit::hashmap! {
            "建筑状态".to_string() => "BaseDataVariableType".to_string(),
            "能源数据".to_string() => "BaseDataVariableType".to_string(),
            "安全状态".to_string() => "BaseDataVariableType".to_string(),
            "环境质量".to_string() => "BaseDataVariableType".to_string(),
        }
    }
    
    fn validate_config(&self) -> Result<()> {
        Ok(())
    }
    
    fn get_scenario_type(&self) -> ScenarioType {
        ScenarioType::CampusOperations
    }
}

// ========== 子配置结构定义 ==========

/// 物料追溯配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialTraceabilityConfig {
    pub enabled: bool,
    pub batch_size: usize,
    pub retention_days: u32,
    pub trace_level: TraceLevel,
}

/// 追溯级别
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TraceLevel {
    Batch,
    Item,
    Lot,
}

/// 生产订单配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProductionOrdersConfig {
    pub enabled: bool,
    pub max_concurrent_orders: usize,
    pub order_priority_rules: Vec<String>,
    pub scheduling_algorithm: SchedulingAlgorithm,
}

/// 调度算法
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SchedulingAlgorithm {
    FIFO,
    PriorityBased,
    ResourceOptimized,
}

/// 设备监控配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EquipmentMonitoringConfig {
    pub enabled: bool,
    pub monitoring_interval_secs: u64,
    pub alert_thresholds: AlertThresholds,
    pub predictive_maintenance: bool,
}

/// 质量检测配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityInspectionConfig {
    pub enabled: bool,
    pub inspection_criteria: Vec<String>,
    pub sampling_rate: f64,
    pub auto_rejection: bool,
}

/// 任务调度配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskSchedulingConfig {
    pub max_concurrent_tasks: usize,
    pub task_timeout_secs: u64,
    pub retry_attempts: u32,
    pub priority_strategy: PriorityStrategy,
}

/// 优先级策略
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PriorityStrategy {
    Fixed,
    Dynamic,
    Adaptive,
}

/// 轨迹规划配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrajectoryPlanningConfig {
    pub planning_algorithm: PlanningAlgorithm,
    pub smoothness_factor: f64,
    pub collision_avoidance: bool,
    pub optimization_criteria: Vec<String>,
}

/// 规划算法
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PlanningAlgorithm {
    RRT,
    AStar,
    PRM,
}

/// 安全监控配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SafetyMonitoringConfig {
    pub enabled: bool,
    pub safety_zones: Vec<SafetyZone>,
    pub emergency_stop_conditions: Vec<String>,
    pub safety_metrics: SafetyMetrics,
}

/// 协作机器人配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollaborativeRoboticsConfig {
    pub enabled: bool,
    pub human_robot_interaction: bool,
    pub force_limiting: bool,
    pub speed_limiting: bool,
}

// 其他子配置结构...
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InventoryManagementConfig {
    pub enabled: bool,
    pub reorder_point: f64,
    pub safety_stock: f64,
    pub inventory_turnover: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogisticsTrackingConfig {
    pub enabled: bool,
    pub gps_tracking: bool,
    pub real_time_updates: bool,
    pub delivery_windows: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrafficMonitoringConfig {
    pub enabled: bool,
    pub traffic_flow_sensors: bool,
    pub camera_monitoring: bool,
    pub incident_detection: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExperimentalDataConfig {
    pub data_retention_policy: String,
    pub data_quality_standards: Vec<String>,
    pub experimental_protocols: Vec<String>,
}

// ========== 辅助结构和枚举 ==========

/// 警报阈值配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertThresholds {
    pub critical: f64,
    pub warning: f64,
    pub info: f64,
}

/// 安全区域配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SafetyZone {
    pub zone_id: String,
    pub coordinates: Vec<(f64, f64)>,
    pub max_speed: f64,
    pub restricted_access: bool,
}

/// 安全指标配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SafetyMetrics {
    pub risk_assessment: bool,
    pub compliance_monitoring: bool,
    pub incident_reporting: bool,
}

/// 场景配置验证器
pub struct ScenarioConfigValidator;

impl ScenarioConfigValidator {
    /// 验证所有场景配置
    pub fn validate_all_scenarios(configs: &ScenarioConfigs) -> Result<()> {
        let scenarios = [
            ("manufacturing", &configs.manufacturing as &dyn ScenarioConfig),
            ("robotics", &configs.robotics),
            ("supply_chain", &configs.supply_chain),
            ("transportation", &configs.transportation),
            ("research_education", &configs.research_education),
            ("public_utilities", &configs.public_utilities),
            ("campus_operations", &configs.campus_operations),
        ];
        
        for (name, scenario) in scenarios.iter() {
            if let Err(e) = scenario.validate_config() {
                return Err(anyhow!("Scenario {} configuration error: {}", name, e));
            }
        }
        
        Ok(())
    }
    
    /// 获取场景的评分权重（用于竞赛评分）
    pub fn get_scenario_weight(scenario_type: &ScenarioType) -> f64 {
        match scenario_type {
            ScenarioType::Manufacturing => 1.0,    // 100%
            ScenarioType::Robotics => 0.95,        // 95%
            ScenarioType::SupplyChain => 0.85,     // 85%
            ScenarioType::Transportation => 0.95,  // 95%
            ScenarioType::ResearchEducation => 0.70, // 70%
            ScenarioType::PublicUtilities => 0.85, // 85%
            ScenarioType::CampusOperations => 0.80, // 80%
        }
    }
    
    /// 计算多场景综合权重
    pub fn calculate_comprehensive_weight(enabled_scenarios: &[&str]) -> f64 {
        let mut total_weight = 0.0;
        let mut count = 0;
        
        for scenario in enabled_scenarios {
            let weight = match *scenario {
                "manufacturing" => 1.0,
                "robotics" => 0.95,
                "supply_chain" => 0.85,
                "transportation" => 0.95,
                "research_education" => 0.70,
                "public_utilities" => 0.85,
                "campus_operations" => 0.80,
                _ => 0.0,
            };
            total_weight += weight;
            count += 1;
        }
        
        if count > 0 {
            total_weight / count as f64
        } else {
            0.0
        }
    }
}

/// 默认配置实现
impl Default for ScenarioConfigs {
    fn default() -> Self {
        Self {
            manufacturing: ManufacturingConfig {
                enabled: true,
                supported_device_types: vec, "Robot".to_string(), "PLC".to_string()],
                data_collection_interval_secs: 5,
                quality_standards: vec, "IATF16949".to_string()],
                material_traceability: MaterialTraceabilityConfig {
                    enabled: true,
                    batch_size: 1000,
                    retention_days: 365,
                    trace_level: TraceLevel::Batch,
                },
                production_orders: ProductionOrdersConfig {
                    enabled: true,
                    max_concurrent_orders: 100,
                    order_priority_rules: vec, "priority".to_string()],
                    scheduling_algorithm: SchedulingAlgorithm::PriorityBased,
                },
                equipment_monitoring: EquipmentMonitoringConfig {
                    enabled: true,
                    monitoring_interval_secs: 10,
                    alert_thresholds: AlertThresholds {
                        critical: 90.0,
                        warning: 80.0,
                        info: 70.0,
                    },
                    predictive_maintenance: true,
                },
                quality_inspection: QualityInspectionConfig {
                    enabled: true,
                    inspection_criteria: vec, "surface".to_string()],
                    sampling_rate: 0.1,
                    auto_rejection: true,
                },
            },
            robotics: RoboticsConfig {
                enabled: true,
                supported_protocols: vec, "Profinet".to_string()],
                motion_control_precision: 0.01,
                task_scheduling: TaskSchedulingConfig {
                    max_concurrent_tasks: 10,
                    task_timeout_secs: 300,
                    retry_attempts: 3,
                    priority_strategy: PriorityStrategy::Dynamic,
                },
                trajectory_planning: TrajectoryPlanningConfig {
                    planning_algorithm: PlanningAlgorithm::RRT,
                    smoothness_factor: 0.8,
                    collision_avoidance: true,
                    optimization_criteria: vec, "energy".to_string()],
                },
                safety_monitoring: SafetyMonitoringConfig {
                    enabled: true,
                    safety_zones: vec],
                    safety_metrics: SafetyMetrics {
                        risk_assessment: true,
                        compliance_monitoring: true,
                        incident_reporting: true,
                    },
                },
                collaborative_robotics: CollaborativeRoboticsConfig {
                    enabled: true,
                    human_robot_interaction: true,
                    force_limiting: true,
                    speed_limiting: true,
                },
            },
            // 其他场景的默认配置...
            supply_chain: SupplyChainConfig::default(),
            transportation: TransportationConfig::default(),
            research_education: ResearchEducationConfig::default(),
            public_utilities: PublicUtilitiesConfig::default(),
            campus_operations: CampusOperationsConfig::default(),
        }
    }
}

// 为其他场景配置实现Default trait
impl Default for SupplyChainConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            inventory_management: InventoryManagementConfig {
                enabled: true,
                reorder_point: 50.0,
                safety_stock: 20.0,
                inventory_turnover: 6.0,
            },
            logistics_tracking: LogisticsTrackingConfig {
                enabled: true,
                gps_tracking: true,
                real_time_updates: true,
                delivery_windows: vec],
            },
            supplier_management: SupplierManagementConfig::default(),
            demand_forecasting: DemandForecastingConfig::default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_scenario_config_validation() {
        let configs = ScenarioConfigs::default();
        assert!(ScenarioConfigValidator::validate_all_scenarios(&configs).is_ok());
    }

    #[test]
    fn test_enabled_scenarios() {
        let configs = ScenarioConfigs::default();
        let enabled = configs.enabled_scenarios();
        assert!(enabled.contains(&"manufacturing"));
        assert!(enabled.contains(&"robotics"));
    }

    #[test]
    fn test_scenario_weight_calculation() {
        let enabled = vec;
        assert!(weight > 0.0 && weight <= 1.0);
    }
}